﻿




using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Hotpot.Extensions;
using Hotpot.Validation;
using Hotpot.ViewModels;

namespace Hotpot.Filters
{
    public class ValidationLocalizationActionFilter : IActionFilter
    {
        #region IActionFilter Members

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HotpotViewModel model = filterContext.Controller.ViewData.Model as HotpotViewModel;
            ValidationStateDictionary validationState = filterContext.Controller.ViewData["ValidationState"] as ValidationStateDictionary;

            if (model != null && validationState != null)
                foreach (KeyValuePair<Type, ValidationState> validationStateItem in validationState)
                    foreach (ValidationError error in validationStateItem.Value.Errors)
                        if (!string.IsNullOrEmpty(error.MessageKey))
                            error.LocalizeMessage((key, defaultValue) => model.Localize(key, defaultValue));

            if (validationState != null)
                filterContext.Controller.ViewData.ModelState.AddModelErrors(validationState);
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
        }

        #endregion
    }
}
